package showtime.framework.manager
{
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.utils.Dictionary;

	/**
	 * @project Client
	 * @date 2011-7-25
	 * @author 绿豆蛙
	 * 
	 */
	public class DepthManager
	{
		private const DEPTH_RESERVED:int = 1048575;
		
		private const DEPTH_HIGHEST:int = 2130690045;
		
		private const DEPTH_LOWEST:int = -16383;
		
		private var _container:DisplayObjectContainer = null;
		
		private var _dict:Dictionary = null;
		
		public function DepthManager(container:DisplayObjectContainer)
		{
			_container = container;
			_dict = new Dictionary(true);
			
			var len:int = _container.numChildren;
			var child:DisplayObject = null;
			
			for ( var i:int = 0; i < len; ++i ){
				child = _container.getChildAt( i );
				_dict[ i ] = child;
				_dict[ child ] = i;
			}  
		}
		
		public function addChild(child:DisplayObject):DisplayObject
		{
			var depth:int = _container.numChildren ? _dict[_container.getChildAt(_container.numChildren - 1)] + 1 : 0;
			_dict[depth] = child;
			_dict[child] = depth;
			
			return _container.addChild(child);
		}
		
		public function getDepth(child:DisplayObject):int
		{
			return _dict[child];
		}
		
		public function removeChild(child:DisplayObject):DisplayObject
		{
			delete _dict[_dict[child]];
			delete _dict[child];
			
			return _container.removeChild(child);
		}
		
		public function removeChildAt(depth:int):DisplayObject
		{
			var child:DisplayObject = _dict[ depth ];
			
			if ( child == null ){
				throw( new RangeError("Caution: no child at depth " + depth ) );
			}
			
			delete _dict[ child ];
			delete _dict[ depth ];
			
			return _container.removeChild( child );
		}
		
		public function sort():void
		{
			
		}
	}
}